package com.example.newsapp.ui.screens.mainScreens

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.ColorSpace.Model
import android.graphics.PorterDuff.Mode
import android.util.Log
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.navigation.compose.rememberNavController
import com.example.newsapp.data.compositionLocal.LocalNavControllerTab
import com.example.newsapp.data.`object`.StateSave
import com.example.newsapp.ui.components.newsComponent.CenterNewsList
import com.example.newsapp.ui.components.newsComponent.TopSearchFrame
import com.example.newsapp.ui.components.newsComponent.TopTabList
import java.io.BufferedReader
import java.io.File
import java.io.FileOutputStream
import java.io.FileReader
import java.io.FileWriter
import java.io.InputStream
import java.io.OutputStream
import java.io.Reader

// 新闻界面
@SuppressLint("SdCardPath")
@Composable
fun NewsScreen(modifier: Modifier = Modifier) {
    val navControllerList = rememberNavController()
    // 交互状态
    val interactionSource = remember { MutableInteractionSource() }
    // 刷新状态
    var isRefresh by remember { mutableStateOf(false) }
    // 刷新判断键
    var keyRefresh by remember { mutableStateOf(0) }
    StateSave.isRefresh = isRefresh
    StateSave.keyRefresh = keyRefresh

    // 复制数据库文件到内部存储
    var context = LocalContext.current
    var path = "/data/data/com.example.newsapp/databases"
    var databasesName = "app_database"
    var reader = context.assets.open(databasesName)
    var file = File(path)
    if (!file.exists()) {
        file.mkdir()
    }
    file.mkdir()
    var writer = FileOutputStream(File(path, databasesName))
    var buffer = ByteArray(1024)
    var length = 0
    while (reader.read(buffer).also { length = it } > 0) {
        writer.write(buffer, 0, length)
    }
    reader.close()
    writer.flush()
    writer.close()

    Column(
        modifier = Modifier.fillMaxSize()
    ) {
        Box {
            // 顶部搜素框
            TopSearchFrame(interactionSource)
        }
        CompositionLocalProvider(
            LocalNavControllerTab provides navControllerList
        ) {
            // 顶部标签栏
            TopTabList()
            // 中间新闻列表
            CenterNewsList()
        }
    }
}